import router from "@/router";
import { message } from "ant-design-vue";
import axios from "axios";
import store from '../store';

const instance = axios.create({
  baseURL: process.env.NODE_ENV === 'production'
  ? ''
  : 'http://127.0.0.1:3000/',
  timeout: 1000,
})

instance.interceptors.request.use(function (config) {
  // Do something before request is sent
  if (store.state.authorizationData !== '') {
    config.headers.common['Authorization'] = 'Bearer ' + store.state.authorizationData
  }
  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

// Add a response interceptor
instance.interceptors.response.use(function (response) {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  console.log('axios response', response)
  if (response.data.Status == 0) {
    return response
  } else {
    message.info(response.data.Message)
  }

  return Promise.reject(response.data);
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  // console.log("interceptors error", error.response)
  if (error.response != undefined && error.response.status === 401) {
    // 认证失败，跳转到登录
    console.log("request 401 to Login page")
    router.push({ name: 'Login' })
  } else {
    message.info('系统错误，请稍后再试: ' + error)
    console.log('request error', error)
  }
  return Promise.reject(error);
});

export default instance;